<?php
defined('BASEPATH') or die('forbidden');

class Cdkeycreate_controller extends Controller {

	private $inc;
	private $channels;
	private $keytypeList;
	private $tmpconnect;
	private $giftbagid;
	//private $channelList;
	const insertnum = 5000;  //每次插入5000条数据
	
    function _init() {
        check_level(50, segment(0), segment(1), segment(2, 'index'));
        set_time_limit(0);
        
        $this->inc = $this->config['inc'];
        $this->channels = $this->inc['allchannel'];
        $this->channels['IosFeiLiuAppStore'] = 'IosFeiLiuAppStore';
        array_push($this->channels, '渠道无关');
        
        $this->tmpconnect = $this->load->database('db') or die("load failed!".mysql_error());
        $sql = "SELECT * FROM cdkey_type";
        $this->tmpconnect->query($sql);
        while($n = $this->tmpconnect->get_array('default'))
        {
        	$this->keytypeList[$n['type']] = $n['name'];
        	$this->giftbagid[$n['type']] = $n['giftbagid'];
        	//$this->channelList[$n['type']] = $n['channel'];
        }
    }

    /*Array ( [channels] => 2 [keytype] => 2 [starttime] => 2015-12-01 17:03:27 [endtime] => 2015-12-18 17:03:39 
     [rewardobjectid] => 1550110010 [number] => 100 )*/
    /*function index() {
     	if (is_submit()) {
            $rowdata = $_POST['row'];
            //var_dump($rowdata);
            //exit(0);
            $rowdata['channel'] = $this->channels[$rowdata['channel']];
            //1.取出表中已有的keychar
            $tmpsql = "SELECT keyChar FROM cdkey";
            $this->tmpconnect->query($tmpsql) or die("query failed!".mysql_error());
            while($n = $this->tmpconnect->get_array())
            {
            	$mysqlrow[] = $n['keyChar'];
            }
            //print_r($rowdata);
            //exit(0);
            //2.生成指定数量的不同的keychar,对比不同则可插入数据库，不过则继续生成
            do{
            	$createrow = $this->cdkeyCreate($rowdata['number']);
            	$realrow[] = array_diff($createrow, $mysqlrow);
            }while(count($realrow)>=$rowdata['number']);
            //print_r($createrow);
            //echo "++++++++";
            print_r($realrow);
            exit(0);
            //3.插入数据库
            //拼接字符串
            $realstr = "INSERT INTO cdkey(keyChar,channel,keytype,starttime,endtime,rewardobjectid) VALUES";
            for ($i = 0; $i < $rowdata['number']; $i++)
            {
            	$realstr .= "('".$realrow[$i]."','".$rowdata['channels']."',".$rowdata['keytype'].",'".$rowdata['starttime']."','".$rowdata['endtime']."'," .$rowdata['rewardobjectid']."),";
            }
            $realstr = substr($realstr,0,strlen($realstr)-1);
            print_r($realstr);
            exit(0);
            $res = $this->tmpconnect->query($sql);
            cp_tips ( true == $res ? "success" : "error" );
        }
        
        //$data['row']=$rowdata;
        $this->view->assign("channel", $this->form->select("row[channels]", $this->channels, '', array('id' => 'channel')));
        foreach ($this->keytypeList as $k => $v)
        {
        	$tmprow[$k] = $k."-".$v;
        }
        $this->view->assign("keytype", $this->form->select("row[keytype]", $tmprow, '', array('id' => 'keytype')));
        $this->view->display("cdkey/cdkeycreate/index");
    }*/
    function index() {
    	if (is_submit()) 
    	{
    		$rowdata = $_POST['row'];
    		//var_dump($rowdata);
    		//exit();
    		if ($rowdata['channels'] == 'shzmTest')
    		{
    			$rowdata['channels'] = 'PCChannel';
    		}
    		if ($rowdata['number'] > 50000) //考虑到插入数据库需要很多时间还有insert...values字符串过长，所以作此限定
    		{
    			echo "<script>alert('create cdkey fail!!! createnumber must be less 50000');</script>";
    			
    			$this->view->assign("channel", $this->form->select("row[channels]", $this->channels, '', array('id' => 'channel')));
    			foreach ($this->keytypeList as $k => $v)
    			{
    				$tmprow[$k] = $k."-".$v;
    			}
    			$this->view->assign("keytype", $this->form->select("row[keytype]", $tmprow, '', array('id' => 'keytype')));
    			$this->view->display("cdkey/cdkeycreate/index");
    			return;
    		}
    		//var_dump($rowdata);
    		//exit(0);
    		//$rowdata['channel'] = $this->channels[$rowdata['channel']];
    		$rowdata['createtime'] = date('Y-m-d H:i:s', time());
    		//拼接字符串
    		if ($rowdata['number']/(self::insertnum) < 1)//可以一次性插入数据库
    		{
    			$realstr = "INSERT INTO cdkey(keyChar,channel,keytype,starttime,endtime,rewardobjectid,createtime) VALUES";
    			for ($i = 0; $i < $rowdata['number']; $i++)
    			{
    				$tmpstr = strtoupper (substr(md5(uniqid(mt_rand(),true)), 0, 16)); //截取16位
    				$realstr .= "('".$tmpstr."','".$rowdata['channels']."',".$rowdata['keytype'].",'".$rowdata['starttime']."','".$rowdata['endtime']."'," .$this->giftbagid[$rowdata['keytype']].", '".$rowdata['createtime']."'),";
    			}
    			$realstr = substr($realstr,0,strlen($realstr)-1);
    			$res = $this->tmpconnect->query($realstr);
    		}
    		else//分次插入数据库，每次5000
    		{
    			$circle = intval($rowdata['number']/(self::insertnum));
    			$restnum = $rowdata['number']%(self::insertnum);
    			
    			for ($i = 0; $i < $circle; $i++)
    			{
    				$realstr = "INSERT INTO cdkey(keyChar,channel,keytype,starttime,endtime,rewardobjectid,createtime) VALUES";
    				for($j = 0; $j < (self::insertnum); $j++) 
    				{
						$tmpstr = strtoupper (substr(md5(uniqid(mt_rand(),true)), 0, 16)); //截取16位
						$realstr .= "('" . $tmpstr . "','" . $rowdata['channels'] . "'," . $rowdata ['keytype'] . ",'" . $rowdata ['starttime'] . "','" . $rowdata ['endtime'] . "'," . $this->giftbagid[$rowdata['keytype']]. ", '" . $rowdata ['createtime'] . "'),";
					}
					$realstr = substr ( $realstr, 0, strlen ( $realstr ) - 1 );
					$res = $this->tmpconnect->query ( $realstr );
    			}
    			$realstr = "INSERT INTO cdkey(keyChar,channel,keytype,starttime,endtime,rewardobjectid,createtime) VALUES";
    			if ($restnum != 0)
    			{
    				for($k = 0; $k < $restnum; $k ++)
    				{
						$tmpstr = strtoupper (substr(md5(uniqid(mt_rand(),true)), 0, 16)); //截取16位
						$realstr .= "('" . $tmpstr . "','" . $rowdata['channels'] . "'," . $rowdata ['keytype'] . ",'" . $rowdata ['starttime'] . "','" . $rowdata ['endtime'] . "'," . $this->giftbagid[$rowdata['keytype']] . ", '" . $rowdata ['createtime'] . "'),";
					}
					$realstr = substr ( $realstr, 0, strlen ( $realstr ) - 1 );
					$res = $this->tmpconnect->query ( $realstr );
				}
    		}
    		
    	    if ($res == true)
    	    	echo "<script>alert('create cdkey success!!! amount:".$rowdata['number']."');</script>";
    	}
    	//$data['row']=$rowdata;
    	$this->view->assign("channel", $this->form->select("row[channels]", $this->channels, '', array('id' => 'channel')));
    	foreach ($this->keytypeList as $k => $v)
    	{
    		$tmprow[$k] = $k."-".$v;
    	}
    	$this->view->assign("keytype", $this->form->select("row[keytype]", $tmprow, '', array('id' => 'keytype')));
    	$this->view->display("cdkey/cdkeycreate/index");
    }
    /*
	static function createcdkey($length = 10) {
		// 密码字符集，可任意添加你需要的字符
		$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
		$password = "";
		for($i = 0; $i < $length; $i ++) {
			// 这里提供两种字符获取方式
			// 第一种是使用 substr 截取$chars中的任意一位字符；
			// 第二种是取字符数组 $chars 的任意元素
			// $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
			$password .= $chars [mt_rand ( 0, strlen ( $chars ) - 1 )];
		}
		return $password;
	} 
	*/
    function cdkeyCreate($number)
    {
    	for ($i = 0; $i < $number; $i++)
    	{
    		$rows[] = strtoupper(uniqid('KEY'));
    	}
    	return $rows;
    }
}

?>
